package org.example.service;

import org.example.entity.SearchResult;
import org.example.DAO.UContentDao;
import org.example.entity.UContent;
import org.example.impl.UContentDaoImpl;
import org.example.Util.DataSourceUtil;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

public class UContentService {
    private final UContentDao uContentDao;

    public UContentService() {
        DataSource dataSource = DataSourceUtil.getDataSource();
        this.uContentDao = new UContentDaoImpl(dataSource);
    }

    public List<SearchResult> searchContent(String query, String type, int limit, int offset) throws SQLException {
        String sql = buildSearchSql(type);
        return uContentDao.searchContent(sql, query, type, limit, offset);
    }

    public int getSearchCount(String query, String type) throws SQLException {
        String sql = buildCountSql(type);
        return uContentDao.getSearchCount(sql, query, type);
    }

    public UContent getContentById(int id) throws SQLException {
        return uContentDao.getContentById(id);
    }

    private String buildSearchSql(String type) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT id, type, title, ");

        if ("movie".equals(type)) {
            sql.append("director AS author, ");
        } else if ("book".equals(type)) {
            sql.append("author, ");
        } else {
            sql.append("artist AS author, ");
        }

        sql.append("release_year AS year, description, image_url, rating, rating_count ");
        sql.append("FROM contents ");
        sql.append("WHERE (title LIKE ? OR description LIKE ? OR ");

        if ("movie".equals(type)) {
            sql.append("director LIKE ?) ");
        } else if ("book".equals(type)) {
            sql.append("author LIKE ?) ");
        } else {
            sql.append("artist LIKE ?) ");
        }

        if (!"all".equals(type)) {
            sql.append("AND type = ? ");
        }

        sql.append("ORDER BY rating DESC, rating_count DESC ");
        sql.append("LIMIT ? OFFSET ?");

        return sql.toString();
    }

    private String buildCountSql(String type) {
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT COUNT(*) FROM contents ");
        sql.append("WHERE (title LIKE ? OR description LIKE ? OR ");

        if ("movie".equals(type)) {
            sql.append("director LIKE ?) ");
        } else if ("book".equals(type)) {
            sql.append("author LIKE ?) ");
        } else {
            sql.append("artist LIKE ?) ");
        }

        if (!"all".equals(type)) {
            sql.append("AND type = ?");
        }

        return sql.toString();
    }
}